package com.vic.kjlink.order.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.AsyncHandlerInterceptor;

import com.vic.kjlink.order.controller.BaseOrderController;
import com.vic.kjlink.order.model.User;
import com.vic.kjlink.order.service.IndexService;

/**
 * 登录验证
 * 
 * @author Vic.xu
 * @description:
 * @date: 2021/8/20 0020 17:09
 */
public class AuthenticationIntercepter implements AsyncHandlerInterceptor {

    private IndexService indexService;

    public AuthenticationIntercepter(IndexService indexService) {
        this.indexService = indexService;
    }

    public AuthenticationIntercepter() {}

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

        User user = BaseOrderController.currentUser();
        if (user == null) {
            user = indexService.ifLogin(request);
            if (user != null) {
                request.getSession().setAttribute(BaseOrderController.PRINCIPAL, user);
                return true;
            }
            // 只用到session和cookie中均不存在用户的时候才拦截去登录页面
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        }

        return true;
    }
}
